package com.cskaoyan.demo2.controller;

import com.cskaoyan.demo2.db.domain.MarketStorage;
import com.cskaoyan.demo2.service.AdminStorageService;
import com.cskaoyan.demo2.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;


@RestController
@RequestMapping("admin/storage")
public class AdminStorageController {

    @Autowired
    AdminStorageService adminStorageService;

    @PostMapping("create")
    public Object create(MultipartFile file){
        String fileName = file.getOriginalFilename();
        long size = file.getSize();
        String contentType = file.getContentType();
        String key = UUID.randomUUID() + "-" + fileName;
        MarketStorage marketStorage = new MarketStorage();
        //制定一个访问当前地址的规则 可以自己去自定义
        //这个url可以这么去写，如果这么去写的话，后续你应当清楚，如果主机、端口号更改，那么图片便无法正常显示，但是只要你的功能逻辑没有问题，后续重新上传依然是可以的
        //看你如何取舍，你觉得这个是不是问题，能不能接受这个问题
        String domain = "http://localhost:80";
        //
        marketStorage.setUrl(domain + "/wx/storage/fetch/" + key);
        marketStorage.setSize((int)size);
        marketStorage.setName(fileName);
        marketStorage.setType(contentType);
        marketStorage.setKey(key);
        marketStorage.setDeleted(false);
        marketStorage.setAddTime(LocalDateTime.now());
        //后续修改数据的时候，只需要去修改更新时间即可
        marketStorage.setUpdateTime(LocalDateTime.now());


        //文件写到某个地方？？？？
        //
        //从context域中读取
        String path = "D:/image";
//        String path = "D:/image";
        try {
            file.transferTo(new File(path + "/" + key));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        adminStorageService.create(marketStorage);
        Object ok = ResponseUtil.ok(marketStorage);
        return ok;
    }
}
